package controller

import (
	"context"
	"errors"
	"goods_product_srv/data_source"
	"goods_product_srv/models"
	seckill "goods_product_srv/proto/seckill"
	"goods_product_srv/utils"
	"time"
)

type Seckills struct {

}

// 查询活动列表
func (s *Seckills)SeckillsList(ctx context.Context, in *seckill.SeckillsRequest, out *seckill.SeckillsResponse) error {
	// 接收参数
	currentPage := in.CurrentPage
	pageSize := in.PageSize

	// 查询总页数
	var total int32
	seckillsTotal := models.SecKills{}
	data_source.Db.Find(&seckillsTotal).Count(&total)

	// 查询数据
	seckills := []models.SecKills{}
	offectNum := (currentPage - 1) * pageSize
	find := data_source.Db.Limit(pageSize).Offset(offectNum).Find(&seckills)

	// fmt.Println(seckills)

	if find.Error != nil {
		out.Msg = "服务器错误"
		out.Code = 500
		return errors.New("服务器错误")
	}else {

		// 需要返回的数据
		seckillsResponse := []*seckill.Seckill{}
		for _, value := range seckills {
			temp := &seckill.Seckill{}
			temp.Id = int32(value.Id)
			temp.Name = value.Name
			temp.Price = value.Price
			temp.Num = int32(value.Num)
			/*
				使用pid查询商品名称
			*/
			product := models.Product{}
			data_source.Db.Where("id = ?", value.PId).First(&product)
			temp.ProductName = product.Name

			temp.ProductId = int32(value.PId)
			temp.StartTime = value.StartTime.Format("2006-01-02 15:04:05")
			temp.EndTime = value.EndTime.Format("2006-01-02 15:04:05")
			temp.CreateTime = value.CreateTime.Format("2006-01-02 15:04:05")
			seckillsResponse = append(seckillsResponse, temp)
		}
		// fmt.Println(seckillsResponse)



		out.Code = 200
		out.Msg = "查询数据成功"
		out.Seckills = seckillsResponse
		out.PageSize = pageSize
		out.Current = currentPage
		out.Total = total
		return nil
	}
}

// 查询商品
func (s *Seckills)GetProducts(ctx context.Context, in *seckill.ProductRequest, out *seckill.ProductResponse) error {
	data := []models.Product{}
	result := data_source.Db.Find(&data)
	if result.Error != nil {
		out.Code = 500
		out.Msg = "没有查询到商品信息"
	}


	productsRes := []*seckill.Product{}
	for _, v := range data {
		temp := seckill.Product{}
		temp.Id = int32(v.Id)
		temp.Pname =  v.Name
		productsRes = append(productsRes, &temp)
	}

	// fmt.Println(productsRes)
	out.Products = productsRes
	out.Code = 200
	out.Msg = "查询成功"

	return nil
}

// 添加活动
func (s *Seckills)SecillsAdd(ctx context.Context, in *seckill.SeckillsAddRequest, out *seckill.SeckillsAddResponse) error {
	// 接收参数
	name := in.Name
	price := in.Price
	num := in.Num
	pid := in.ProductId
	startTime := in.StartTime
	endTime := in.EndTime
	// 保存到数据库
	seckills := models.SecKills{
		Name:       name,
		Price:      price,
		Num:        int(num),
		PId:        int(pid),
		Status:		0,
		StartTime:  utils.StrTimeToTime(startTime),
		EndTime:    utils.StrTimeToTime(endTime),
		CreateTime: time.Now(),
	}
	err := data_source.Db.Create(&seckills).Error

	if err != nil {
		out.Code = 500
		out.Msg = "添加活动失败"
		return nil
	}else {
		out.Code = 200
		out.Msg = "添加活动成功"
		return nil
	}

}

// 活动编辑页面显示数据
func (s *Seckills)ToEditSeckill(ctx context.Context, in *seckill.ToEditSeckillRequest, out *seckill.ToEditSeckillResponse) error {
	// 接收参数
	id := in.Id
	// 查询数据
	temp := models.SecKills{Id:int(id)}
	err := data_source.Db.Find(&temp).Error
	//fmt.Println(temp)
	if err != nil {
		out.Code = 500
		out.Msg = "服务器错误"
		return errors.New("服务器错误")
	}
	// 通过商品id来查询活动关联的商品
	product := models.Product{Id:temp.PId}
	err2 := data_source.Db.First(&product).Error
	// fmt.Println(product)

	// 查询关联商品的id和name
	products := []models.Product{}
	data_source.Db.Where("id != ?", temp.PId).Find(&products)

	resPro := []*seckill.Product{}
	for _, v := range products {
		temp := seckill.Product{}
		temp.Id = int32(v.Id)
		temp.Pname = v.Name

		resPro = append(resPro, &temp)
	}


	if err2 != nil {
		res := seckill.Seckill{
			Id:          int32(temp.Id),  // 活动id
			Name:        temp.Name,
			Price:       temp.Price,
			Num:         int32(temp.Num),
			ProductId:   0,     // 商品id
			ProductName: "",
			StartTime:   temp.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:     temp.EndTime.Format("2006-01-02 15:04:05"),
		}

		out.Code = 200
		out.Msg = "查询成功"
		out.Seckills = &res


		return nil


	}else {
		res := seckill.Seckill{
			Id:          int32(temp.Id),  // 活动id
			Name:        temp.Name,
			Price:       temp.Price,
			Num:         int32(temp.Num),
			ProductId:   int32(product.Id),        // 商品id
			ProductName: product.Name,
			StartTime:   temp.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:     temp.EndTime.Format("2006-01-02 15:04:05"),
		}

		out.Code = 200
		out.Msg = "查询成功"
		out.Seckills = &res
		out.ProductsNo = resPro


		return nil
	}

}

// 编辑活动
func (s *Seckills)DoEditSeckill(ctx context.Context, in *seckill.DoEditSeckillRequest, out *seckill.DoEditSeckillResponse) error {
	// 接收参数
	id := in.Id
	name := in.Name
	price := in.Price
	num := in.Num
	pid := in.ProductId
	startTime := in.StartTime
	endTime := in.EndTime
	// 保存到数据库
	seckill := models.SecKills{
		Id:         int(id),
		Name:       name,
		Price:      price,
		Num:        int(num),
		PId:		int(pid),
		StartTime:  utils.StrTimeToTime(startTime),
		EndTime:    utils.StrTimeToTime(endTime),
		CreateTime: time.Now(),
	}
	db := data_source.Db.Model(&seckill).Updates(seckill)
	if db.Error != nil {
		out.Code = 500
		out.Msg = "更新活动失败"
	}else {
		out.Code = 200
		out.Msg = "更新活动成功"
	}
	return nil
}

// 删除活动
func (s *Seckills)DeleteSeckill(ctx context.Context, in *seckill.DeleteSeckillRequest, out *seckill.DeleteSeckillResponse) error {
	// 接收参数
	id := in.Id
	// 删除数据
	delSeckill := models.SecKills{Id: int(id)}
	err := data_source.Db.Delete(&delSeckill).Error
	if err != nil {
		out.Code = 500
		out.Msg = "删除活动失败"
	}else {
		out.Code = 200
		out.Msg = "删除活动成功"
	}


	return nil
}


/*
前端展示活动
 */
func (s *Seckills)FrontSeckillsList(ctx context.Context, in *seckill.FrontSeckillsRequest, out *seckill.FrontSeckillsResponse) error {
	// 接收参数
	currentPage := in.CurrentPage
	pageSize := in.PageSize


	/*
	过滤查询数据

	只显示未来一天要做的活动  当前时间加一天 >= 开始时间
	未下架的活动
	 */
	// 查询数据
	modelSeckills := []models.SecKills{}
	offsetNum := (currentPage - 1) * pageSize   // 分页查询

	limitTime := utils.AddHour(24)
	err := data_source.Db.Where("start_time <= ?", limitTime).Where("status = 0").Limit(pageSize).Offset(offsetNum).Find(&modelSeckills).Error


	// 查询总页数
	var total int32
	seckillsTotal := []models.SecKills{}
	data_source.Db.Where("start_time <= ?", limitTime).Where("status = 0").Find(&seckillsTotal).Count(&total)





	// fmt.Println(modelSeckills)
	if err != nil {
		out.Msg = "服务器错误"
		out.Code = 500
		return errors.New("服务器错误")
	}else {
		// 需要返回的数据
		seckillsResponse := []*seckill.FrontSeckill{}
		for _, value := range modelSeckills {
			temp := &seckill.FrontSeckill{}
			temp.Id = int32(value.Id)
			/*
				使用pid查询商品
			*/
			product := models.Product{}
			data_source.Db.Where("id = ?", value.PId).First(&product)
			temp.ProductName = product.Name
			temp.OldPrice = product.Price   // 商品的价格
			temp.Pic = product.Pic  // 商品图片
			temp.ProductDesc = product.Desc

			temp.NewPrice = value.Price     // 秒杀价格
			seckillsResponse = append(seckillsResponse, temp)
		}
		// fmt.Println(seckillsResponse)


		out.Code = 200
		out.Msg = "查询数据成功"
		out.SeckillList = seckillsResponse
		out.PageSize = pageSize
		out.CurrentPage = currentPage
		out.TotalPage = (total + pageSize - 1) / pageSize
		return nil
	}
}

func (s *Seckills)FrontSeckillsDetail(ctx context.Context, in *seckill.DetailRequest, out *seckill.DetailResponse) error {
	id := in.Id

	// 查询数据  单个查询
	modelsSeckill := models.SecKills{}
	err := data_source.Db.Where("id = ?", id).Find(&modelsSeckill).Error
	if err != nil {
		out.Code = 500
		out.Msg = "服务器内部错误"
		return errors.New("服务器内部错误")
	}
	// 查询商品
	modelsProduct := models.Product{}
	err2 := data_source.Db.Where("id = ?", modelsSeckill.PId).Find(&modelsProduct).Error

	if err2 != nil {
		out.Code = 500
		out.Msg = "服务器内部错误"
		return errors.New("服务器内部错误")
	}

	out.Id = int32(modelsSeckill.Id)
	out.NewPrice = modelsSeckill.Price
	out.Num = int32(modelsSeckill.Num)
	out.StartTime = modelsSeckill.StartTime.Format("2006-01-02 15:04:05")
	out.EndTime = modelsSeckill.EndTime.Format("2006-01-02 15:04:05")
	out.Name = modelsSeckill.Name   // 活动名字

	out.Unit = modelsProduct.Uint
	out.Pic = modelsProduct.Pic
	out.Desc = modelsProduct.Desc   // 商品描述

	out.Code = 200
	out.Msg = "OK"
	return nil
}
